package com.atguigu.gmall.mq;


import com.atguigu.gmall.mq.service.impl.RabbitServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;


@Configuration
@Import(RabbitServiceImpl.class)
@Slf4j
@EnableRabbit //开启mq功能
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class AppRabbitAutoConfiguration {

    @Bean
    public RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate();
        configurer.configure(template, connectionFactory);

        /**
         * message： 刚才的消息
         * replyCode： 回复码；
         * replyText： 回复文本；
         * exchange：交换机
         * routingKey：路由键
         */
        //return回调
        template.setReturnCallback((Message message, int replyCode, String replyText,
                                    String exchange, String routingKey) -> {
            log.info("消息为：{}，拒绝码为：{}，拒绝内容为：{}，交换机为：{}，路由键为：{}"
                    , message, replyCode, replyText, exchange, routingKey);
        });

        /**
         * CorrelationData：刚才发送的消息的相关数据
         * ack: 确认状态，代表服务器的exchange是否收到
         * cause： 如果有问题，会打印错误原因
         */
        //confirm回调
        template.setConfirmCallback((CorrelationData correlationData, boolean ack,String cause) -> {
            log.info("消息为：{}，是否收到：{}，错误原因：{}"
                    , correlationData, ack, cause);
        });
        return template;
    }
}
